<template>
    <div class="app-container">
      <el-card class="box-card">
        <el-button type="primary" @click="addSubmit">更新盲盒</el-button>
        <el-button type="primary" @click="testBlindBox">测试盲盒</el-button>
        <el-button type="primary" @click="handleAdd">添加礼物</el-button>
        <el-button type="primary" @click="handleViewData">查看数据</el-button>
        <el-button type="primary" @click="handleViewLog">查看记录</el-button>

        <div class="infoBox">
			<el-form ref="form1" :inline="false" :model="formData1" :rules="rules1" label-width="120px" size="normal">
				<el-form-item label="盲盒名称" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示盲盒名称，可以修改，更新盲盒之后显示新名字" />
				</el-form-item>
				<el-form-item label="盲盒排序" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="与礼物排序公用一个接口" />
				</el-form-item>
				<el-form-item label="返奖率" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="" disabled />
				</el-form-item>
				<el-form-item label="盲盒价格" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示盲盒当前开启的价格">
						<template slot="append">M豆</template>
					</el-input>
				</el-form-item>
				<el-form-item label="盲盒介绍" prop="giftId">
					<el-input v-model="formData1.picture" placeholder="显示创建上传的图片地址" />
					<el-upload
						ref="upload"
						:auto-upload="true"
						:before-upload="beforeAvatarUpload"
						:http-request="customizeUpload"
						:on-remove="handleSpecialFlagBigRemove1"
						:on-success="handleSpecialFlagBigSuccess1"
						action=""
						:show-file-list="false"
						class="upload-demo"
					>
						<el-button slot="trigger" size="small" type="primary">上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="最小期望值" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示礼物池里面最小的期望值" disabled />
				</el-form-item>
				<el-form-item label="盲盒图片" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示创建上传的图片地址" />
					<el-upload
						ref="upload"
						:auto-upload="true"
						:before-upload="beforeAvatarUpload"
						:http-request="customizeUpload"
						:on-remove="handleSpecialFlagBigRemove2"
						:on-success="handleSpecialFlagBigSuccess2"
						action=""
						class="upload-demo"
						list-type="picture"
					>
						<el-button slot="trigger" size="small" type="primary">上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="盲盒详情" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示创建上传的图片地址" />
					<el-upload
						ref="upload"
						:auto-upload="true"
						:before-upload="beforeAvatarUpload"
						:http-request="customizeUpload"
						:on-remove="handleSpecialFlagBigRemove3"
						:on-success="handleSpecialFlagBigSuccess3"
						action=""
						class="upload-demo"
						list-type="picture"
					>
						<el-button slot="trigger" size="small" type="primary">上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="最大期望值" prop="giftId">
					<el-input v-model="formData1.giftId" placeholder="显示礼物池里面最大的期望值" disabled />
				</el-form-item>
				
			</el-form>
        </div>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          border
          class="mt-3"
          stripe
          style="width: 100%"
          tooltip-effect="dark"
        >
          <el-table-column label="序号" type="index" :index="indexMethod" prop="user_code" width="80px"></el-table-column>
          <el-table-column label="礼物ID" prop="gift_id"></el-table-column>
          <el-table-column label="礼物名称" prop="gift_name"></el-table-column>
          <el-table-column label="赠送数量" prop="give_num"></el-table-column>
          <el-table-column label="总产出数量" prop="output_num"></el-table-column>
          <el-table-column label="礼物总价值（M豆）" prop="gift_total_value"></el-table-column>
          <el-table-column label="实际概率（%）" prop="level1_rate"></el-table-column>
          <el-table-column label="显示概率（%）" prop="level11_rate"></el-table-column>
          
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleEditOrAdd(scope)"
              >编辑
              </el-button>
              
              <el-button
                size="mini"
                type="text"
                @click="handleStatus(scope.$index)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <!-- <cus-pagination
          v-show="total > 0"
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getTableData"
        /> -->
    </el-card>

	<el-dialog
        :visible.sync="dialogVisible1"
        title="测试盲盒"
        width="30%"
        @close="closeDialog('form')"
    >
        <el-form ref="form2" :inline="false" :model="formData2" :rules="rules2" label-width="150px" size="normal">
          <el-form-item label="测试用户编号" prop="giftId">
            <el-input
              v-model="formData.giftId"
              placeholder="输入测试用户的编号（多个编号用英文的逗号隔开）"
            />
          </el-form-item>
          
        </el-form>
  
        <span slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditOrAdd(null)">确定</el-button>
        </span>
    </el-dialog>
  
    <el-dialog
        :visible.sync="dialogVisible"
        title="添加礼物"
        width="30%"
        @close="closeDialog('form')"
    >
        <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="120px" size="normal">
          <el-form-item label="礼物ID" prop="giftId">
            <el-input
              v-model="formData.giftId"
              placeholder="请输入礼物ID"
            />
          </el-form-item>
          
        </el-form>
  
        <span slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditOrAdd(null)">确定</el-button>
        </span>
    </el-dialog>
  
    <el-dialog
        :visible.sync="dialogVisible2"
        title="添加礼物"
        width="30%"
        @close="closeDialog2"
    >
        <el-form ref="form2" :inline="false" :model="giftFormData" :rules="giftFormRules" label-width="120px" size="normal">
			<el-form-item label="礼物ID：">
				<el-input placeholder="礼物ID" v-model="giftFormData.gift_id" disabled></el-input>
			</el-form-item>
			<el-form-item label="礼物名称：">
				<el-input placeholder="礼物名称" v-model="giftFormData.gift_name" disabled></el-input>
			</el-form-item>
			<el-form-item label="礼物单价：">
				<el-input placeholder="礼物单价" v-model.number="giftFormData.price" disabled>
					<template slot="append">M豆</template>
				</el-input>
			</el-form-item>
			<el-form-item label="兑换数量：" prop="give_num">
				<el-input placeholder="请输入兑换数量" v-model.number="giftFormData.give_num">
					<template slot="append">个</template>
				</el-input>
			</el-form-item>
			<el-form-item label="兑换所需数量：" prop="output_num">
				<el-input placeholder="请输入兑换所需数量" v-model.number="giftFormData.output_num" :disabled="giftFormData.outputNumShow">
					<template slot="append">个</template>
				</el-input>
			</el-form-item>
			<el-form-item label="产出总数量：" prop="output_num">
				<el-input placeholder="请输入产出总数量" v-model.number="giftFormData.output_num" :disabled="giftFormData.outputNumShow">
					<template slot="append">个</template>
				</el-input>
				<el-checkbox v-model="giftFormData.outputNumShow" @change="handleChange">不限</el-checkbox>
			</el-form-item>
			
        </el-form>
  
        <span slot="footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </el-dialog>
  
    </div>
</template>
  
<script>
    import { giftList, listData, addOrEdit, calcData } from '@/api/mokaCrystal'
  
  	export default {
        name: 'anchorList',
        components: {},
        data() {
        return {
            dialogVisible: false,
			dialogVisible1: false,
            dialogVisible2: false,
            input2: undefined,
			outputNumShow: false,
			unit_price: undefined,
			min_expected_val: undefined,
			min_giveback_rate: undefined,
			max_giveback_rate: undefined,
			max_expected_val: undefined,
			banner_price: undefined,
            giftFormData: {
				id: null,
				outputNumShow: false,
				gift_id: undefined,
				gift_name: undefined,
				price: undefined,
				output_num: undefined,
				give_num: undefined
            },
			giftFormRules: {
				output_num: [{ required: true, message: '请输入产出总数量', trigger: 'blur' }],
				give_num: [{ required: true, message: '请输入赠送数量', trigger: 'blur' }]
            },
            formData: {
              	giftId: undefined
            },
            rules: {
              	giftId: [{ required: true, message: '请输入礼物ID', trigger: 'blur' }]
            },
			formData1: {
              	giftId: undefined,
				picture: undefined
            },
			rules1: {
              	giftId: [{ required: true, message: '请输入礼物ID', trigger: 'blur' }],
				picture: [{ required: true, message: '请上传盲盒介绍', trigger: 'blur' }]
            },
			formData2: {
              	giftId: undefined
            },
            rules2: {
              	giftId: [{ required: true, message: '输入测试用户的编号（多个编号用英文的逗号隔开）', trigger: 'blur' }]
            },
            title: '',
            loading: false,
            form: {
             	session: ''
            },
            banForm: {
              	reason: ''
            },
            tableData: [],
            listQuery: {
				page: 1,
				perPage: 10
            },
            total: 1,
			pool_id: undefined,
			index: undefined
        }
    },
    created() {
		this.listQuery.id = this.$route.query.rowId == 0 ? 0 : this.$route.query.rowId ? this.$route.query.rowId : undefined
        this.getTableData()
    },
    methods: {
		indexMethod(index) {
			return this.tableData.length - index
		},
        handleInput(val,key) {
			// val.toString().match(/^\d+(?:\.\d{0,3})?/)
			console.log(val.toString())
			val = val.replace(/\.{2,}/g,".");//一个小数点
			val = val.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
			val = val.replace(/^(\-)*(\d+)\.(\d{0,6}).*$/,'$1$2.$3');//小数点后6位
			this.giftFormData[key] = val
        },
		addSubmit() {
			if(!this.unit_price) {
				this.$message({
					type: 'warning',
					message: '开启单价不能为空'
				})
				return false
			}
			if(this.tableData.length === 0) {
				this.$message({
					type: 'warning',
					message: '请添加礼物'
				})
				return false
			}
			const data = {
				gifts: this.tableData,
				pool_id: this.pool_id,
				unit_price: Number(this.unit_price),
				banner_price: Number(this.banner_price)
			}
			this.addOrEditGift(data)
		},
		testBlindBox() {
			this.dialogVisible1 = true
		},
		handleChangeUnit() {
			this.calcDataFun()
		},
		calcDataFun() {
			const data = {
				gifts: this.tableData,
				unit_price: Number(this.unit_price)
			}
			calcData(data).then(res => {
				if(res.code === 200) {
					this.min_expected_val = res.data.min_expected_val
					this.min_giveback_rate = res.data.min_giveback_rate
					this.max_giveback_rate = res.data.max_giveback_rate
					this.max_expected_val = res.data.max_expected_val
					this.banner_price = res.data.banner_price
				}
			})
		},
		addOrEditGift(data) {
			addOrEdit(data).then(res => {
				if(res.code === 200) {
					this.dialogVisible2 = false
					console.log(this.listQuery.id)
					// if(this.listQuery.id) {
					// 	this.getTableData()
					// }else {
					// 	this.calcDataFun()
					// }
					this.getTableData()
				}
			})
		},
		// 查看数据
		handleViewData() {
			this.$router.push({
				path: 'blindBoxData',
				query: {
					poolId: this.pool_id
				}
			})
		},
		// 查看记录
		handleViewLog() {
			this.$router.push({
				path: 'blindBoxRecord',
				query: {
					poolId: this.pool_id
				}
			})
		},
    
        // 网络请求
        /**
         * getTableData
         * @desc 获取表格数据
         */
        async getTableData() {
            this.loading = true
            for (let key in this.listQuery) {
                this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
            }
            const detail = await listData(this.listQuery)
			console.log(this.listQuery.id)
            if (detail.code === 200) {
				if(this.listQuery.id == 0 || this.listQuery.id) {
					this.pool_id = detail.data.data[Number(this.listQuery.id)].id
					this.unit_price = detail.data.data[Number(this.listQuery.id)].unit_price
					this.min_expected_val = detail.data.data[Number(this.listQuery.id)].min_expected_val
					this.min_giveback_rate = detail.data.data[Number(this.listQuery.id)].min_giveback_rate
					this.max_giveback_rate = detail.data.data[Number(this.listQuery.id)].max_giveback_rate
					this.max_expected_val = detail.data.data[Number(this.listQuery.id)].max_expected_val
					this.banner_price = detail.data.data[Number(this.listQuery.id)].banner_price
					this.tableData = detail.data.data[Number(this.listQuery.id)].gifts
				}else {
					this.tableData = []
				}
				for(let item of this.tableData) {
					if(item.output_num === 0) {
						item.outputNumShow = true
					}else {
						item.outputNumShow = false
					}
				}
            }
            this.loading = false
    
        },
        closeDialog(form) {
            if (this.$refs[form]) {
                // this.formData.status = undefined
                this.$refs[form].clearValidate() // 清除整个表单的校验
                this.$refs[form].resetFields() // 清除整个表单的校验
            }
        },
		closeDialog2() {
			this.outputNumShow = false
			this.giftFormData = {
				id: null,
				outputNumShow: false,
				gift_id: undefined,
				gift_name: undefined,
				price: undefined,
				output_num: undefined,
				give_num: undefined
			}
        },
        handleAdd() {
          this.dialogVisible = true
        },
        handleEditOrAdd(scope) {
          if(scope) {
            // 编辑
            console.log('编辑',scope.row)
			this.giftFormData = JSON.parse(JSON.stringify(scope.row))
			this.giftFormData.id = this.giftFormData.id || 0
			this.index = scope.$index
			this.dialogVisible2 = true
          }else {
            // 新增
            this.checkedGiftList(this.formData.giftId)
          }
          
        },
		onSubmit() {
            this.$refs['form2'].validate(valid => {
                if (valid) {
					
					for (let key in this.giftFormData) {
						this.giftFormData[key] = this.giftFormData[key] === '' || this.giftFormData[key] === undefined ? 0 : this.giftFormData[key]
					}
					console.log(this.giftFormData.id)
					
					this.giftFormData.gift_total_value = this.giftFormData.give_num * this.giftFormData.price
					if(this.giftFormData.id || this.giftFormData.id === 0) {
						
						this.$set(this.tableData,this.index,this.giftFormData)
					}else {
						this.giftFormData.id = undefined
						
						this.tableData.unshift(this.giftFormData)
					}
					this.calcDataFun()
					this.dialogVisible2 = false
                }
            })
        },
		checkedGiftList(id) {
			this.$refs['form'].validate(valid => {
                if (valid) {
					giftList(id).then(res => {
						if(res.code === 200) {
							this.dialogVisible2 = true
							this.dialogVisible = false
							this.giftFormData.gift_id = res.data.id
							this.giftFormData.price = res.data.price
							this.giftFormData.gift_name = res.data.name
						}
					})
                }
            })
		},
        handleStatus(index) {
            this.tableData.splice(index, 1)
			this.calcDataFun()
        },
        async handleEditLevel(form) {
            this.$refs[form].validate(valid => {
                if (valid) {
                    if(this.formData.status === 1) {
                        this.$confirm('当前有进行中的摩卡水晶奖池，不能开启多个进行中的摩卡水晶奖池', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消删除'
                            });
                        });
                    }
                    if(this.formData.status === 2) {
                        this.$prompt('请输入测试人员ID：', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPattern: /^[0-9]/,
                            inputErrorMessage: '请输入正确的测试人员ID'
                        }).then(({ value }) => {
                            this.$message({
                                type: 'success',
                                message: '你的邮箱是: ' + value
                            });
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '取消输入'
                            });       
                        });
                    }
                } else {
                    return false
                }
            })
        },
		handleChange(val) {
			if(val) {
				this.giftFormData.output_num = 0
			}
		},
		beforeAvatarUpload(file) {
			// const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
			// const isLt2M = file.size / 1024 / 1024 < 2

			// if (!isJPG) {
			// 	this.$message.error('请上传JPG/PNG格式的图片!')
			// }
			// if (!isLt2M) {
			// 	this.$message.error('上传图片大小不能超过 2MB!')
			// }
			// return isJPG && isLt2M
		},
		handleSpecialFlagBigSuccess1() {
			this.formData1.picture = this.ossLastImgUrl
		},
		handleSpecialFlagBigRemove1() {
			this.specialFlagBigList = []
		},
		handleSpecialFlagBigSuccess2() {
			this.editRulesForm.picture = this.ossLastImgUrl
		},
		handleSpecialFlagBigRemove2() {
			this.specialFlagBigList = []
		},
		handleSpecialFlagBigSuccess3() {
			this.editRulesForm.picture = this.ossLastImgUrl
		},
		handleSpecialFlagBigRemove3() {
			this.specialFlagBigList = []
		},
    }
  }
</script>
  
<style lang="scss" scoped>
.infoBox {
  margin-top: 15px;
  margin-bottom: 15px;
  padding-top: 22px;
  border: 1px solid #999999;
  border-radius: 10px;

}
.upload-demo {
	margin-left: 10px;
}
::v-deep {
	.infoBox{
		.el-form{
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			justify-content: flex-start;
			.el-form-item {
				width: 30% !important;
			}
			.el-form-item__content {
				display: flex;
				align-items: center;
			}
		}
	}
}

</style>
  